﻿namespace MicroCloud.Audit
{
    /// <summary>
    /// 审计模块DTO实体映射
    /// </summary>
    public class AutoMapperAuditConfiguration : AutoMapperTupleBase
    {
        /// <summary>
        /// 初始化一个审计模块DTO实体映射 <see cref="AutoMapperAuditConfiguration"/> 的新实例
        /// </summary>
        /// <param name="provider">服务提供者</param>
        public AutoMapperAuditConfiguration(IServiceProvider provider)
        {
            ServiceProvider = provider;
        }

        #region 属性
        /// <summary>
        /// 获取 服务提供者
        /// </summary>
        protected IServiceProvider ServiceProvider { get; }

        #endregion

        #region IMapTuple
        /// <summary>
        /// 创建对象映射
        /// </summary>
        public override void CreateMap()
        {
            CreateMap<AuditOperation, AuditOperationOutputDto>()
                .ForMember(dto => dto.UserName, opt => opt.MapFrom(entity => GetUser(ServiceProvider, entity.UserId).UserName))
                .ForMember(dto => dto.UserNickname, opt => opt.MapFrom(entity => GetUser(ServiceProvider, entity.UserId).NickName));
        }

        #endregion

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <param name="provider">服务提供者</param>
        /// <param name="userId">用户编号</param>
        /// <returns></returns>
        protected static UserSimpleDto GetUser(IServiceProvider provider, string userId)
        {
            if (userId.IsMissing())
            {
                return new UserSimpleDto();
            }
            using IServiceScope scope = provider.CreateScope();
            var userRepository = scope.ServiceProvider.GetService<IRepository<User, long>>();
            var user = userRepository.QueryAsNoTracking().Where(o => o.Id == userId.CastTo<long>()).ToCacheFirst<User, UserSimpleDto>(10, false, nameof(UserSimpleDto));
            return user ?? new UserSimpleDto();
        }

    }

}
